<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrapper">
      <div class="title">
        基本信息
      </div>
      <el-form :model="dataForm" class="el-form__two" ref="dataForm" label-width="200px" :rules="roleRules">
        <el-row>
          <!-- 第1行 -->
          <el-form-item prop="businessId" label="商户">
            <el-select :disabled="true" class="readonly" v-model="dataForm.businessId" @change="handleBusinessIdChange"
              clearable filterable>
              <el-option v-for="item in businessList" :key="item.id" :value="item.id" :label="item.name">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="部门:" prop="departIds">
            <el-cascader v-model="dataForm.departIds" :options="departList" clearable filterable
              :props="{ value: 'departId', label: 'departName', checkStrictly: true }">

            </el-cascader>
          </el-form-item>

          <el-form-item label="产品类别" prop="goodsType">
            <el-select class="readonly" v-model="dataForm.goodsType" disabled>
              <el-option v-for="item in $Options.serverTypeList" :value="item.id" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="classifyIds" label="产品分类">
            <el-cascader :disabled="true" class="readonly" :key="cascaderKey" clearable filterable v-model="dataForm.classifyIds"
              :options="treeThreeServerList" :props="{ label: 'classifyName', value: 'serverClassifyId' }">
            </el-cascader>
          </el-form-item>
          <!-- <el-form-item label="对接类型" prop="dockingType" v-show="dataForm.dockingFlag==2">
            <el-select class="readonly" v-model="dataForm.dockingType" disabled>
              <el-option v-for="item in $Options.dockingTypeList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item prop="name" label="产品名称:" placeholder="请输入产品名称">
            <el-input type="text" v-model="dataForm.name" clearable></el-input>
          </el-form-item>
          <el-form-item prop="businessClassifyIds" label='商户分类'>
            <el-select class="business-classify_select readonly" disabled
                       v-model="dataForm.businessClassifyIds" clearable filterable multiple>
              <el-option v-for="item in businessClassifyList" :value="item.id" :label="item.name" :key="item.id">
                <div class="business-classify_name" v-html="item.name">

                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="saleState" label="产品状态:">
            <el-select v-model="dataForm.saleState">
              <el-option v-for="item in $Options.saleStateList" :label="item.name" :value="item.id" :key="item.id">

              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="ghModelId" label='可售时间模板'>
            <el-select v-model="dataForm.ghModelId" @change="handleGhModelIdChange" clearable filterable>
              <el-option v-for="item in goodsHoursList" :label='item.modelName' :value="item.modelId" :key="item.modelId">

              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item prop="doctorId" label="关联医生">
            <el-select v-model="dataForm.doctorId" clearable filterable>
              <el-option v-for="item in doctorList" :value="item.id" :label="item.name" :key='item.id'></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item prop="businessConfirmWay" label="商户确认方式:">
            <el-select v-model="dataForm.businessConfirmWay">
              <el-option v-for="item in $Options.businessConfirmWayList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="waiters" label="服务员:" v-if="dataForm.serverType==4&&!dataForm.specs.length">
            <el-select v-model="dataForm.waiters" multiple value-key="id" @change="handleWaiterIdsChange">
              <el-option v-for="item in waiterList" :label="item.name" :value="item" :key="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="押金" prop="deposit" type="number" v-if="dataForm.goodsType == 3">
            <el-input type="number" v-model.number="dataForm.deposit" clearable @input="handleMoneyInput(4)">
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="visitFlag" label="是否上门:">
            <el-radio-group v-model="dataForm.visitFlag" @change="handleFlagChange(1)">
              <el-radio  :label="1">是</el-radio>
              <el-radio  :label="0">否</el-radio>
            </el-radio-group>

          </el-form-item>
          <el-form-item prop="shopFlag" label="是否到店:">
            <el-radio-group v-model="dataForm.shopFlag"  @change="handleFlagChange(2)">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="remoteFlag" label="是否远程:">
            <el-radio-group v-model="dataForm.remoteFlag"  @change="handleFlagChange(3)">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="fastFlag" label="紧急通知:">
            <el-radio v-model="dataForm.fastFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.fastFlag" :label="0">否</el-radio>
          </el-form-item>
          <el-form-item prop="backFlag" label="是否必须归还:" v-show="dataForm.goodsType==3">
            <el-radio v-model="dataForm.backFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.backFlag" :label="0">否</el-radio>
          </el-form-item>
          <el-form-item prop="dockingFlag" label="是否对接">
            <el-radio-group v-model="dataForm.dockingFlag" @change="dataForm.dockingType=''" disabled>
              <el-radio  :label="1">否</el-radio>
              <el-radio  :label="2">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="huskFlag" label="是否为空包产品:">
            <el-radio v-model="dataForm.huskFlag" :label="1" class="readonly" disabled>是</el-radio>
            <el-radio v-model="dataForm.huskFlag" :label="0" class="readonly" disabled>否</el-radio>
          </el-form-item>
          <el-form-item prop="specDisplayType" label="多规格单项展示方式">
            <el-radio-group v-model="dataForm.specDisplayType" :disabled="specDisplayType">
              <el-radio  :label="0">默认</el-radio>
              <el-radio  :label="1">页面展示</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="title" v-show="dataForm.dockingFlag==2">对接信息</div>
      <el-form v-show="dataForm.dockingFlag==2" :model="dataForm" class="el-form__two" label-width="200px">
        <el-row>
          <el-form-item prop="dockingType" label="对接类型" v-show="dataForm.dockingFlag==2" >
            <el-select class="readonly" v-model="dataForm.dockingType" @change="dataForm.doctorId='';dataForm.itemCode=''" disabled>
              <el-option v-for="item in $Options.dockingTypeList" :value="item.id" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="doctorId" label="关联医生" v-show="dataForm.dockingType==1">
            <el-select v-model="dataForm.doctorId" clearable filterable class="readonly" disabled>
              <el-option v-for="item in doctorList" :value="item.id" :label="item.name" :key='item.id'></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="itemCode" label="项目编码" v-show="dataForm.dockingType==2">
            <el-input class="readonly" v-model="dataForm.itemCode" clearable disabled>

            </el-input>
          </el-form-item>
          <el-form-item prop="itemName" label="项目名称" v-show="dataForm.dockingType==2">
            <el-input class="readonly" v-model="dataForm.itemName" clearable disabled >

            </el-input>
          </el-form-item>

        </el-row>
      </el-form>
      <div class="title" v-show="!dataForm.huskFlag">
        价格信息
      </div>
      <el-form v-show="!dataForm.huskFlag"  :model="dataForm" class="el-form__two" ref="dataForm2" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item prop="price" label="平台原价:">
            <el-input type="number" :disabled="dataForm.goodsType==15?true:false" v-model.number="dataForm.price" @input="handleMoneyInput(0)" clearable>
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
          <el-form-item label="平台售价:" prop="salePrice">
            <el-input type="number" :disabled="dataForm.goodsType==15?true:false" v-model.number="dataForm.salePrice" @input="handleMoneyInput(1)" clearable>
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
          <el-form-item label="商户原价:" prop="marketPrice">
            <el-input type="number" :disabled="dataForm.goodsType==15?true:false" v-model.number="dataForm.marketPrice" @input="handleMoneyInput(5)"
              @blur="handleMarketPriceBlur" clearable>
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
          <el-form-item prop="discount" label="商户折扣比例:">
            <el-input style="position:relative" type="number" :disabled="dataForm.goodsType==15?true:false" v-model.number="dataForm.discount"
              @blur="handleDiscountBlur" @input="handleDiscountInput" clearable>
              <span slot="suffix">%</span>
            </el-input>
          </el-form-item>
          <el-form-item label="成本价:" prop="costPrice">
            <el-input type="number" :disabled="dataForm.goodsType==15?true:false" v-model.number="dataForm.costPrice" @input="handleMoneyInput(2)"
              @blur="handleCostBlur" clearable>
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="stock" label="总库存">
            <el-input :readonly="true" v-model="dataForm.stock" clearable @input="handleStockInput"></el-input>
          </el-form-item>
          <el-form-item prop="packageFee" label="包装费:">
            <el-input type="number" v-model.number="dataForm.packageFee" clearable @input="handleMoneyInput(3)">
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
          <el-form-item prop="packageFlag" label="包装费计算方式">
            <el-radio v-model="dataForm.packageFlag" :label="1">独立包装费</el-radio>
            <el-radio v-model="dataForm.packageFlag" :label="2">合并包装费</el-radio>
          </el-form-item>
          <el-form-item prop="fastFlag" label="是否需配送费:">
            <el-radio v-model="dataForm.deliveryFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.deliveryFlag" :label="0">否</el-radio>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="title" v-if="dataForm.ghModelId">
        可售时间
      </div>
      <el-row style="width:96%;margin:0 auto;" v-if="dataForm.ghModelId">
        <el-table :data="dataForm.goodsHours" style="width:fit-content;max-width:fit-content;margin-bottom:10px">
          <el-table-column type="index" label="序号" align="center" width="100px">
          </el-table-column>
          <el-table-column prop="beginHours" label="开始时间" align="center" width="200">
          </el-table-column>
          <el-table-column prop="endHours" label="结束时间" align="center" width="200">
          </el-table-column>
          <el-table-column prop="estimateTime" label="最快到达时间" align="center" width="200">
            <template slot-scope="scope">
              {{ scope.row.estimateTime }}{{ formatTimeUnit(scope.row.timeUnit) }}
            </template>
          </el-table-column>
          <el-table-column prop="deliveryTime" label="可送时间段" align="center" width="200">
          </el-table-column>
          <el-table-column prop="businessRemindTime" label="商户提醒时间(分)" align="center" width="140">
          </el-table-column>
          <el-table-column prop="waiterRemindTime" label="服务员提醒时间(分)" align="center" width="140">
          </el-table-column>
        </el-table>
      </el-row>
      <div class="title">
        产品视频图片与规格
      </div>
      <el-row style="width: 96%;margin: 0 auto;">
        <div class="flex-box">
          <div class="server-img">
            <span class="label">*</span>
            产品视频图片
          </div>
          <div class="btn-wrapper">
            <el-button type="danger" size="mini" @click="showImageSelectDialog = true">复制公共图库</el-button>
          </div>
        </div>

        <UploadOssFile :list="fileList" @getImgVideo="getImgVideo" folder="goodsImg"></UploadOssFile>
        <GoodsSpec
          v-show="!dataForm.huskFlag"
          :forbid="true"
          ref="goodsSpec"
          :mainImg="mainImg"
          :info="dataForm"
          :specList="dataForm.specs"
          :tableList="dataForm.goodsVariants"
          :saleState="true"
          :serverType="dataForm.goodsType"
          folder="goodsImg"
          :sort="false">
        </GoodsSpec>
      </el-row>
      <div class="title">
        商品详情描述
      </div>
      <el-row style="width: 96%;margin: 0 auto;">
        <div class="introduce">
          <div class="item">
            <div class="label">
              产品简介
            </div>
            <el-input rows="4" type="textarea" maxlength="200" show-word-limit v-model="dataForm.introduce" placeholder="请输入简介"></el-input>
          </div>
          <div class="item">
            <div class="label">
              备注
            </div>
            <el-input rows="4" type="textarea" v-model="dataForm.remark" placeholder="请输入备注"></el-input>
          </div>
        </div>
        <RichEditor :richText="dataForm.describes" @getRichText="getRichText"></RichEditor>
      </el-row>
      <el-row class="bottom"
        :style="{ width: !$store.getters.sidebar.opened ? 'calc(100vw - 87px)' : 'calc(100vw - 239px)' }">
        <div class="wrapper">
          <div class="back" @click="returnList">
            返回
          </div>
          <div class="save" @click="sureClick()">
            保存
          </div>
        </div>
      </el-row>
    </div>

    <ImageSelect :show="showImageSelectDialog" folder="goodsImg" :limit="limitNum" @cancel="showImageSelectDialog = false"
      @getUrlList="getUrlList"></ImageSelect>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import GoodsApi from '@/api/goods/goods';
import BusinessApi from "@/api/business/business";
import ServerClassifyApi from "@/api/server/serverClassify"
import BusinessDepartApi from "@/api/business/depart"
import { getStorage } from '@/utils/auth'
import { USER_INFO } from "@/constants/storeName"
import UploadImg from "../../components/UploadImg.vue";
import GoodsSpec from "../../components/GoodsSpec.vue";
import RichEditor from "../../components/RichEditor.vue";
import UploadOssFile from "../../components/UploadOssFile.vue";
import ImageSelect from "../../components/ImageSelect.vue";
import TimeTemplateApi from '@/api/goods/timeTemplate';
import DoctorApi from "@/api/institution/doctor";
import BusinessServerApi from '@/api/goods/businessServer'
import WaiterApi from "@/api/business/waiter";
export default {
  data() {
    return {
      cascaderKey: 1,
      dataForm: {
        goodsId: "",
        //sort:"",
        dockingType:"",
        dockingFlag:1,
        // doctorId:"",
        businessId: "",
        classifyIds: [],
        // businessClassifyIds:[],
        goodsType: 1,
        deposit: "",
        stock: "",
        name: "",
        departIds: [],
        goodsImages: [],
        introduce: "",
        describes: "",
        businessConfirmWay:1,
        visitFlag: 1,//是否上门，1代表是
        shopFlag: 0,//是否到店，1代表是，0代表不是
        remoteFlag: 0,//是否远程，1代表是，0代表不是
        fastFlag: 0,//紧急通知
        backFlag:1,//是否必须归还 1表示是 0表示不是
        deliveryFlag: 0,//是否需配送费
        packageFlag:1,//包装费计算方式(1.独立包装费(默认) 2.合并包装费)
        huskFlag:0,
        saleState: 2,//1 待上架 2上架 3下架 4当日售罄
        price: "",
        discount: "",
        salePrice: "",
        costPrice: "",
        deliveryFee: "",
        packageFee: "",
        marketPrice: "",
        remark: "",
        specs: [],
        goodsVariants: [],
        variantState: 1,
        goodsCode: "",
        ghModelId: "",
        goodsHours: [
        ],
        dockingFlag:1,
        doctorId:"",
        itemCode:"",
        itemName:"",
        businessClassifyIds:[],
        specDisplayType:0,
        waiters:[],
        relationWaiters:[
          // {
          //   waiterId:"",
          //   waiterName:"",
          //   prepareTime:"",// 准备时间
          //   serviceTime:""// 结束时间
          // }
        ],
      },
      fileList: [],
      businessList: [],
      treeThreeServerList: [],
      waiterList:[],
      loadingIns: false,
      roleRules: {
        businessId: [
          { required: true, message: "请选择商户", trigger: "change" }
        ],
        name: [
          { required: true, message: "请输入产品名称", trigger: "blur" }
        ],
        price: [
          { required: true, type: 'number', message: "请输入平台原价", trigger: "blur" }
        ],
        salePrice: [
          { required: true, type: 'number', message: "请输入平台售价", trigger: "blur" }
        ],
        costPrice: [
          { required: true, type: 'number', message: "请输入成本价", trigger: "blur" }
        ],
        discount: [
          { required: true, type: "number", message: "请输入收费比例", trigger: "blur" }
        ],
        marketPrice: [
          { required: true, type: 'number', message: "请输入商户原价", trigger: "blur" }
        ],
        deposit: [
          { required: true, type: 'number', message: "请输入押金", trigger: "blur" }
        ],
      },
      departList: [],
      showImageSelectDialog: false,
      limit: 5,
      goodsHoursList: [],
      businessClassifyList:[],
      doctorList:[],
    }
  },
  components: {
    UploadImg,
    GoodsSpec,
    RichEditor,
    UploadOssFile,
    ImageSelect
  },
  computed: {
    mainImg() {
      let val = this.dataForm.goodsImages.find(item => item.mainFlag)
      return val ? val.url : ""
    },
    limitNum() {
      return this.limit - this.dataForm.goodsImages.length
    },
    specDisplayType(){
      if(this.dataForm.specs.length==1){
        return false
      } else{
        this.dataForm.specDisplayType = 0
        return true
      }
    }
  },
  mounted() {
    this.init()
  },
  watch: {
    treeThreeServerList() {
      this.cascaderKey++
    },
    "dataForm.goodsType": {
      handler(val) {
        if (val == 3) {
          this.roleRules.deposit = { required: true, type: 'number', message: "请输入押金", trigger: "blur" }
        } else {
          this.$delete(this.roleRules, 'deposit')
        }

        if(val==4&&!this.dataForm.specs.length){
          this.roleRules.waiters = { required: true, message: "请选择服务员", trigger: "change" }
        }else{
          this.$delete(this.roleRules, 'waiters')
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      },
      immediate: true
    }
  },
  methods: {
    async init() {
      // 获取用户的角色信息
      await this.getWaiterList()
      this.getBusinessList()
      if (this.$route.query.id) {
        this.dataForm.goodsId = this.$route.query.id
        this.getData()
      }
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    async getData() {
      const res = await GoodsApi.getGoodsInfo({id: this.dataForm.goodsId})
      const data = res.data
      //if(res.data.sort==999)res.data.sort = ""
      // 这里需要将二三级分类id变为数组
      const classifyIds = []
      data.serverClassifyId ? classifyIds.push(data.serverClassifyId) : ""
      data.thirdClassifyId ? classifyIds.push(data.thirdClassifyId) : ''
      data.classifyIds = classifyIds

      // 将四级部门合并为数组
      const departIds = []
      data.departId ? departIds.push(data.departId) : ""
      data.firstDepartId ? departIds.push(data.firstDepartId) : ""
      data.secondDepartId ? departIds.push(data.secondDepartId) : ""
      data.thirdDepartId ? departIds.push(data.thirdDepartId) : ""
      data.departIds = departIds


      // 如果存在商户分类就需要获取
      data.businessClassifyIds = (data.businessClassifies || []).map(item => item.id)

       // 处理规格列表
       data.goodsVariants&&data.goodsVariants.forEach(item=>item.moreImg = item.moreImg?item.moreImg.split(","):[])

      this.fileList = JSON.parse(JSON.stringify(data.goodsImages || []))
      this.$Utils.bindingBean(this.dataForm, data)
      this.getTreeThreeServerList()
      this.getDepartList()
      this.getGoodsHoursList()

      await this.getBusinessClassifyList()
      this.getBusinessClassifyStyle()
      // 存在商户分类就获取关联医生
      if(data.businessClassifyIds.length>0)this.getDoctorList()

    },
    // 获取服务员
    async getWaiterList(){
      const {data} = await WaiterApi.listIdName({ jobType:1})
      this.waiterList = data||[]
    },
    getDepartList() {
      BusinessDepartApi.listMangerTree({ businessId: this.dataForm.businessId }).then(res => {
        this.setDisabled(res.data)
        this.departList = res.data
      })
    },
    setDisabled(list) {
      list.forEach(item => {
        if (!item.power) {
          item.disabled = true
        }
        if (item.children) {
          this.setDisabled(item.children)
        }
      })
    },
    async getDoctorList(){
      let {businessClassifyIds} = this.dataForm
      businessClassifyIds = businessClassifyIds.toString()
      // console.log(this.businessClassifyList.filter(item=>this.dataForm.businessClassifyIds.some(item2=>item2==item.id)))
      // const officeIds = this.businessClassifyList
      // .filter(item=>this.dataForm.businessClassifyIds.some(item2=>item2==item.id))
      // .map(item=>item.value)
      // .filter(item=>item).toString()
      if(!businessClassifyIds) return
      const {data} = await DoctorApi.getDoctorNames({businessClassifyIds})
      this.doctorList = data||[]
    },
    handleGhModelIdChange() {
      const { dataForm, goodsHoursList } = this
      dataForm.goodsHours = []
      if (!dataForm.ghModelId) return
      const val = goodsHoursList.find(item => item.modelId == dataForm.ghModelId)
      if (val) {
        dataForm.goodsHours = val.relations
      }
    },
    formatTimeUnit(cell) {
      if (cell == 1) {
        return "分钟"
      } else if (cell == 2) {
        return "时"
      } else {
        return ""
      }
    },
    getGoodsHoursList() {
      TimeTemplateApi.listIdName({ businessId: this.dataForm.businessId }).then(res => {
        this.goodsHoursList = res.data
      })
    },
    getUrlList(val) {
      this.fileList = JSON.parse(JSON.stringify(this.dataForm.goodsImages.concat(val)))
      this.showImageSelectDialog = false
    },
    getRichText(val) {
      this.dataForm.describes = val
    },
    handleBusinessIdChange() {
      this.dataForm.classifyIds = []
      this.treeThreeServerList = []
      this.dataForm.departIds = []
      this.goodsHoursList = []
      this.dataForm.ghModelId = ""
      this.dataForm.goodsHours = []
      this.dataForm.businessClassifyIds = []
      this.businessClassifyList = []
      this.departList = []
      if (this.dataForm.businessId) {
        this.getTreeThreeServerList()
        this.getDepartList()
        this.getGoodsHoursList()
        this.getBusinessClassifyList()
      }
      this.handleBusinessClassifyChange()
    },
     // 商户分类改变
    //  handleBusinessClassifyChange () {
    //   this.dataForm.doctorId = ""
    //   this.doctorList = []
    //   if(this.dataForm.businessClassifyIds.length > 0){
    //     this.getDoctorList()
    //   }
    //   this.$nextTick(() => {
    //     const {businessClassifyList, dataForm} = this
    //     const els = document.querySelectorAll('.business-classify_select .el-select__tags-text')
    //     dataForm.businessClassifyIds.forEach((item, index) => {
    //       const obj = businessClassifyList.find(item2 => item2.id == item)
    //       els[index].innerHTML = obj.name
    //     })
    //   })
    // },
    // 获取上传的文件列表
    getImgVideo(val) {
      this.dataForm.goodsImages = val
    },
    // 获取商户列表
    getBusinessList() {
      BusinessApi.listIdNameVo().then(res => {
        this.businessList = res.data
      })
    },
    // 获取产品分类列表
    getServerClassifyList() {
      let param = { level: 2 }
      if (this.dataForm.businessId) {
        param.businessId = this.dataForm.businessId
      }
      ServerClassifyApi.listIdName(param).then(res => {
        this.serverClassifyList = res.data
      })
    },
    async getBusinessClassifyList () {
      const res = await BusinessServerApi.classifyListIdName({businessId: this.dataForm.businessId})
      this.businessClassifyList = res.data
      // this.handleBusinessClassifyChange()
    },
    getBusinessClassifyStyle(){
      this.$nextTick(() => {
        const {businessClassifyList, dataForm} = this
        const els = document.querySelectorAll('.business-classify_select .el-select__tags-text')
        dataForm.businessClassifyIds.forEach((item, index) => {
          const obj = businessClassifyList.find(item2 => item2.id == item)
          els[index].innerHTML = obj.name
        })
      })
    },
    // 获取二三级服务列表
    getTreeThreeServerList() {
      let params = {
        level: 2,
      }
      // 是管理员就要选择商户
      params.businessId = this.dataForm.businessId
      ServerClassifyApi.listServerClassify(params).then(res => {
        this.treeThreeServerList = res.data
      })
    },
    handleFlagChange(val){
      const {visitFlag,shopFlag,remoteFlag} = this.dataForm
      switch(val){
        case 1:
          if(visitFlag){
            this.dataForm.shopFlag = 0
            this.dataForm.remoteFlag = 0
          }
          break
        case 2:
          if(shopFlag){
            this.dataForm.visitFlag = 0
            this.dataForm.remoteFlag = 0
          }
          break
        case 3:
        if(remoteFlag){
            this.dataForm.shopFlag = 0
            this.dataForm.visitFlag = 0
          }
          break
      }
    },
    checkData() {

      if (!this.dataForm.huslFlag&&!this.$refs.goodsSpec.checkSpec()) return


      if (this.dataForm.goodsVariants.length) {
        this.dataForm.variantState = 2
        this.goodsVariants = JSON.parse(JSON.stringify(this.dataForm.goodsVariants))
        this.goodsVariants.forEach(item=>item.moreImg=item.moreImg.join(","))
      } else {
        this.dataForm.variantState = 1
      }

      if(this.dataForm.dockingFlag==2&&!this.dataForm.dockingType){
        this.$message.error('对接类型不能为空')
        return false
      }

      if (!this.dataForm.goodsImages.some(item => item.type == 1)) {
        this.$message.error("请至少选择一张产品图片")
        return false
      }

      if (!this.dataForm.goodsImages.some(item => item.type == 1 && item.mainFlag == 1)) {
        this.$message.error("请至少选择一张产品主图")
        return false
      }

      if(this.dataForm.goodsType==4&&!this.dataForm.specs.length){
        for(let item of this.dataForm.relationWaiters){
          if(!item.prepareTime||!item.serviceTime){
            this.$message.error("请把服务员工作时间填写完整")
            return
          }
        }
      }
      return true
    },
    async sureClick() {
      await Promise.all([this.$refs.dataForm.validate(),this.$refs.dataForm2.validate()])
      if (!this.checkData()) return
      await this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
      if (this.dataForm.goodsId) {
        this.editData();
      } else {
        this.addData();
      }
    },
    // 商户原价改变
    handleMarketPriceBlur() {
      const { marketPrice, discount, costPrice } = this.dataForm
      if (costPrice && marketPrice && costPrice > marketPrice) {
        this.dataForm.marketPrice = ""
        this.dataForm.discount = ""
        this.$message.error("商户原价不能小于成本价")
        return
      }

      this.dataForm.costPrice = parseFloat((marketPrice * discount / 100).toFixed(4))
    },
    // 商户折扣比例改变
    handleDiscountBlur() {
      const { marketPrice, discount } = this.dataForm
      this.dataForm.costPrice = parseFloat((marketPrice * discount / 100).toFixed(4))
    },
    handleCostBlur() {
      const { costPrice, marketPrice } = this.dataForm
      if(costPrice==0){
        return
      }
      if (costPrice && marketPrice && costPrice > marketPrice) {
        this.dataForm.marketPrice = ""
        this.dataForm.discount = ""
        this.$message.error("成本价不能大于商户原价")
        return
      }
      this.dataForm.discount = parseFloat((costPrice / marketPrice*100).toFixed(2))
    },
    // 价格或者配送费改变,需要计算出售价
    handleMoneyChange() {
      let price = this.dataForm.price || 0
      let deliveryFee = this.dataForm.deliveryFee || 0
      this.dataForm.salePrice = parseFloat((price + deliveryFee).toFixed(2))
    },
    handleMoneyInput(flag) {
      if (!flag) {
        // 只保留两位小数
        this.dataForm.price = parseFloat(parseFloat(this.dataForm.price).toFixed(2))
        !this.dataForm.price ? this.dataForm.price = 0 : ""
      } else if (flag == 1) {
        this.dataForm.salePrice = parseFloat(parseFloat(this.dataForm.salePrice).toFixed(2))
        !this.dataForm.salePrice ? this.dataForm.salePrice = 0 : ""
      } else if (flag == 2) {
        // 只保留两位小数
        this.dataForm.costPrice = parseFloat(parseFloat(this.dataForm.costPrice).toFixed(4))
        !this.dataForm.costPrice ? this.dataForm.costPrice = 0 : ""
      } else if (flag == 3) {
        // 只保留两位小数
        this.dataForm.packageFee = parseFloat(parseFloat(this.dataForm.packageFee).toFixed(2))
        !this.dataForm.packageFee ? this.dataForm.packageFee = 0 : ""
      } else if (flag == 4) {
        // 只保留两位小数
        this.dataForm.deposit = parseFloat(parseFloat(this.dataForm.deposit).toFixed(2))
        !this.dataForm.deposit ? this.dataForm.deposit = 0 : ""
      }else if (flag == 5) {
        // 只保留两位小数
        this.dataForm.marketPrice = parseFloat(parseFloat(this.dataForm.marketPrice).toFixed(2))
        !this.dataForm.marketPrice ? this.dataForm.marketPrice = 0 : ""
      }
    },
    // 平台比例输入的时候
    handleDiscountInput() {
      this.dataForm.discount = parseFloat(parseFloat(this.dataForm.discount).toFixed(2))
      if (this.dataForm.discount && this.dataForm.discount > 99.72) {
        this.dataForm.discount = 0
        this.$message.error("商户折扣比例只能是0-99.72之间")
      } else if (this.dataForm.discount) {
        this.dataForm.discount = parseFloat(parseFloat(this.dataForm.discount).toFixed(2))
      } else {
        this.dataForm.discount = 0
      }
    },
    // 库存输入
    handleStockInput() {
      this.dataForm.stock = this.dataForm.stock.replace(/[^0-9]|^0/g, "")
    },
    addData() {
      let param = {
        //sort: this.dataForm.sort ? this.dataForm.sort : 999,
        goodsType: this.dataForm.goodsType,
        deposit: this.dataForm.goodsType == 3 ? this.dataForm.deposit : "",
        businessId: this.dataForm.businessId,
        // businessClassifyIds: this.dataForm.businessClassifyIds,
        serverClassifyId: this.dataForm.classifyIds[0] ? this.dataForm.classifyIds[0] : "",
        thirdClassifyId: this.dataForm.classifyIds[1] ? this.dataForm.classifyIds[1] : "",
        name: this.dataForm.name,
        departId: this.dataForm.departIds[0] || "",
        firstDepartId: this.dataForm.departIds[1] || "",
        secondDepartId: this.dataForm.departIds[2] || "",
        thirdDepartId: this.dataForm.departIds[3] || "",
        goodsImages: this.dataForm.goodsImages,
        introduce: this.dataForm.introduce,
        describes: this.dataForm.describes,
        businessConfirmWay:this.dataForm.businessConfirmWay,
        visitFlag: this.dataForm.visitFlag,
        shopFlag: this.dataForm.shopFlag,
        remoteFlag: this.dataForm.remoteFlag,
        fastFlag: this.dataForm.fastFlag,
        backFlag: this.dataForm.goodsType == 3 ? this.dataForm.backFlag : "",
        deliveryFlag: this.dataForm.deliveryFlag,
        packageFlag:this.dataForm.packageFlag,
        saleState: this.dataForm.saleState,
        price: this.dataForm.price,
        discount: this.dataForm.discount,
        salePrice: this.dataForm.salePrice,
        costPrice: this.dataForm.costPrice,
        packageFee: this.dataForm.packageFee,
        marketPrice: this.dataForm.marketPrice,
        remark: this.dataForm.remark,
        specs: this.dataForm.specs,
        goodsVariants: this.goodsVariants,
        goodsHours: this.dataForm.goodsHours,
        ghModelId: this.dataForm.ghModelId,
        dockingType:this.dataForm.dockingType,
        dockingFlag:this.dataForm.dockingFlag,
        specDisplayType:this.dataForm.specDisplayType,
        relationWaiters:this.dataForm.relationWaiters,
      };
      GoodsApi.addGoods(param).then(res => {
        this.$Utils.notifySuccess()
        this.returnList();
      })
    },
    editData() {
      let param = {
        goodsId: this.dataForm.goodsId,
        goodsType: this.dataForm.goodsType,
        deposit: this.dataForm.goodsType == 3 ? this.dataForm.deposit : "",
        businessId: this.dataForm.businessId,
        // businessClassifyIds: this.dataForm.businessClassifyIds,
        serverClassifyId: this.dataForm.classifyIds[0] ? this.dataForm.classifyIds[0] : "",
        thirdClassifyId: this.dataForm.classifyIds[1] ? this.dataForm.classifyIds[1] : "",
        name: this.dataForm.name,
        departId: this.dataForm.departIds[0] || "",
        firstDepartId: this.dataForm.departIds[1] || "",
        secondDepartId: this.dataForm.departIds[2] || "",
        thirdDepartId: this.dataForm.departIds[3] || "",
        goodsImages: this.dataForm.goodsImages,
        introduce: this.dataForm.introduce,
        describes: this.dataForm.describes,
        businessConfirmWay:this.dataForm.businessConfirmWay,
        visitFlag: this.dataForm.visitFlag,
        shopFlag: this.dataForm.shopFlag,
        remoteFlag: this.dataForm.remoteFlag,
        fastFlag: this.dataForm.fastFlag,
        backFlag: this.dataForm.goodsType == 3 ? this.dataForm.backFlag : "",
        deliveryFlag: this.dataForm.deliveryFlag,
        packageFlag:this.dataForm.packageFlag,
        saleState: this.dataForm.saleState,
        price: this.dataForm.price,
        discount: this.dataForm.discount,
        salePrice: this.dataForm.salePrice,
        costPrice: this.dataForm.costPrice,
        packageFee: this.dataForm.packageFee,
        marketPrice: this.dataForm.marketPrice,
        remark: this.dataForm.remark,
        specs: this.dataForm.specs,
        goodsVariants: this.goodsVariants,
        goodsCode: this.dataForm.goodsCode,
        goodsHours: this.dataForm.goodsHours,
        ghModelId: this.dataForm.ghModelId,
        dockingType:this.dataForm.dockingType,
        dockingFlag:this.dataForm.dockingFlag,
        specDisplayType:this.dataForm.specDisplayType,
        relationWaiters:this.dataForm.relationWaiters,
      };
      GoodsApi.editGoods(param)
        .then(data => {
          this.$Utils.notifySuccess()
          this.returnList();
        })
    },
    returnList() {
      this.$store.dispatch('delView', this.$route);
      this.$router.push({ path: '/goods/goodsManagement' });
    }
  },

}
</script>
<style lang="scss" scoped>
@import "@/assets/css/views/serverAdd.scss";
</style>
<style lang="scss" scoped>
.flex-box {
  display: flex;
  align-items: center;

  &>div {
    margin-right: 10px;
  }

  .server-img {
    position: relative;
    font-size: 14px;

    .label {
      color: red;
      position: absolute;
      top: 0;
      left: -12px;
    }
  }
}

.introduce {
  margin-bottom: 10px;
  font-size: 14px;
  display: flex;
  width: 1000px;
  justify-content: space-between;

  .item {
    width: 46%;
    display: flex;
    text-align: end;

    .label {
      width: 80px;
      padding-right: 7px;
    }
  }

}</style>
